package com.fs.uc.api.open.resource;

import com.fs.uc.api.open.dto.*;
import com.fs.uc.base.Const;
import com.fs.uc.base.domain.*;
import com.fs.uc.base.exception.CustomException;
import com.fs.uc.base.repo.*;
import com.fs.uc.core.SubjectType;
import com.fs.uc.core.behavior.ParkBehavior;
import com.fs.uc.security.JwtUtil;
import com.wf.captcha.SpecCaptcha;

import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.awt.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;

/**
 * 公开api
 *
 * @author 崔超
 * 2021/12/2
 */
@Path(Const.URL_PREFIX)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Transactional
public class OpenResource {

    @Inject
    CaptchaRepository captchaRepo;
    @Inject
    OrgRepository orgRepo;
    @Inject
    JwtUtil jwtUtil;
    @Inject
    CheckCodeRepository checkCodeRepo;
    @Inject
    ParkBehavior parkBehavior;

    /*
    注册创建园区租户
     */
    @Path("/public/register")
    @POST
    public void RegisterTenant(@Valid ReqRegister req) {
        if (orgRepo.findByName(req.getOrganization()) != null) {
            throw new CustomException("已存在相同组织名称");
        }
        if (orgRepo.findByLoginName(req.getLoginName()) != null) {
            throw new CustomException("已存在相同登录名");
        }

        CheckCode checkCode = checkCodeRepo.findByPhone(req.getPhone());
        if (checkCode == null) {
            throw new CustomException("请先获取验证码");
        }
        if (!req.getCheckCode().equals(checkCode.code)) {
            throw new CustomException("验证码错误");
        }
        if (checkCode.createTime.plusMinutes(5).isBefore(LocalDateTime.now())) {
            throw new CustomException("验证码过期,请重新获取验证码");
        }

        parkBehavior.create(req.getOrganization(),req.getLoginName(),req.getPassword(),req.getPhone());

    }

    /*
    组织实体账户登录web获取Token
     */
    @POST
    @Path("/login")
    public String getTokenWithCaptcha(@Valid ReqLoginWithCaptcha req) {
        checkCaptcha(req.getKey(), req.getCaptcha());

        Org org = orgRepo.findByLoginNameAndPassword(req.getUsername(), req.getPassword());
        if (org == null) {
            throw new CustomException("用户名或密码错误");
        }

        return jwtUtil.buildToken(org);
    }

    /*
    获取图形验证码
     */
    @Path("/login/captcha")
    @GET
    public RespCaptcha captcha() {
        Font font = Font.getFont("SansSerif");
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 50, 5, font);
        String capText = specCaptcha.toBase64();
        String value = specCaptcha.text();

        String key = UUID.randomUUID().toString();
        Captcha captcha = new Captcha();
        captcha.id = key;
        captcha.value = value;
        captcha.createTime = LocalDateTime.now();
        captchaRepo.persist(captcha);

        return new RespCaptcha(capText, key);
    }

    private void checkCaptcha(String key, String value) {
        Optional<Captcha> optional = captchaRepo.findByIdOptional(key);
        if (optional.isEmpty()) {
            throw new CustomException("验证码错误");
        }
        Captcha captcha = optional.get();
        if (captcha.createTime.plusHours(1).isBefore(LocalDateTime.now())) {
            captchaRepo.deleteById(captcha.id);
            throw new CustomException("验证码过期，请重新刷新验证码");
        }
        if (!captcha.value.equalsIgnoreCase(value)) {
            throw new CustomException("验证码错误");
        }
        captchaRepo.deleteById(captcha.id);
    }
}
